import re

from rest_framework import serializers

from goods.models import SKU
from .models import User
from django_redis import get_redis_connection
from users.utils import generic_verify_url
#因为有模型所以我们用serialzer.ModelSerializer



class RegisterCreateUserSerializer(serializers.ModelSerializer):
    """
    6个参数(mobile,password,password2,username,sms_code,allow)

    """
    #只进行反序列化要求,也就是只需要传入,不需要读取
    #write_only 只在反序列化输入的时候起作用,在序列化(对象-->字典)时不起作用
    #read_only  只读,不反序列化使用

    #user里没有这些字段,我们就写这些字段
    password2 = serializers.CharField(label='确认密码',write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(label='是否同意协议',write_only=True)
    #token只用于返回,返回只读就可以
    token = serializers.CharField(label='token',read_only=True)

    #ModelSerializer 自动生成字段的时候,是根据fields来生成的

    class Meta:

        model = User
        fields = ['id','mobile','password','username','password2','sms_code','allow','token']

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }



    """
        对数据的验证有 4中方式:
            1.字段类型
            2.字段选项
            3.单字段校验
            4.多字段校验

        校验手机号   单个字段校验
        是否同意协议 单个字段校验

        密码和确认密码 多个字段
        短信验证码需要多个字段校验

    """

    def validate_mobile(self,value):

        if not re.match('1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号规则不正确')

        #最终校验完成之后,要把值返回回去
        return value

    def validate_allow(self,value):

        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    def validate(self, attrs):

        #密码和确认密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')

        if password != password2:
            raise serializers.ValidationError('密码不一致')
        #短信验证码需要连接redis

        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')

        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码有误')

        return attrs

    #
    def create(self, validated_data):
        #系统在调用此方法的时候,validated_data多了一些字段,因为User模型
        #中没有那些字段(password2,sms_code,allow),
        #所以我们把validated_data中的这三个字段删除就可以

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create(**validated_data)

        #修改密码
        user.set_password(validated_data['password'])
        user.save()

        #如何生成token,把代码复制到这里

        from rest_framework_jwt.settings import api_settings
        #1.我们需要获取rest_framework_jwt的两个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #2.将用户信息给payload,然后进行编码
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class UserCenterInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email','email_active')

class UserUpdateEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)

    def update(self, instance, validated_data):

        #保存邮件内容
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        #保存完成之后,发送激活邮件
        # from django.core.mail import send_mail
        # # subject,
        # subject = '美多商城激活邮件'
        # #  message,
        # message = '内容'
        # #  from_email,
        # from_email = '美多商城<qi_rui_hua@163.com>'
        # # recipient_list
        # recipient_list = [email]
        #
        # # 我们要生成一个 激活的url
        # # http://ip:port/succes.html?token=xxxx
        # # token 应该包含 用户的信息
        # verify_url = generic_verify_url(instance.id,email)
        #
        # #可以设置丰富的url
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        #
        #
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message
        #           )

        from celery_tasks.email.tasks import send_verify_url
        send_verify_url(instance.id,email)

        return instance
from .models import Address
class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):

        """
        因为我们没有让前端传递过来user,所以我们在进行
        Address.objects.create(**validated_data)时会出错,
        因为缺少了user
        """
        #在提供序列化器对象的时候，REST framework会向对象的context属性
        # 补充三个数据：request、format、view，这三个数据对象可以在定义序列化器时使用
        validated_data['user'] = self.context['request'].user

        # return Address.objects.create(**validated_data)
        #super会调用ModelSerializer的create方法
        return super().create(validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class UserHistorySerializer(serializers.ModelSerializer):

    sku_id = serializers.CharField(label='商品',required=True)

    class Meta:
        model = SKU
        fields = ['sku_id']

    def validate(self, attrs):

        #判断商品id 是否存在
        sku_id = attrs.get('sku_id')
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception:
            raise serializers.ValidationError('商品不存在')

        return attrs


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')